// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package middlewares

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-wares/framework-iris/framework/src/middlewares"
	"github.com/kataras/iris/v12"
	"server/app/http/models"
	"server/app/lib"
	"server/app/lib/authorizer"
)

// MasterMiddleware
// 钓场管理员.
//
// @Name("master")
func MasterMiddleware(i iris.Context) {
	var (
		admin  *models.ArcadeAdmins
		arcade *models.Arcades
		aid    int64
		auth   *authorizer.Authentication
		ctx    context.Context
		err    error
		master = lib.Arcade.GetMaster()
	)

	// 1. 继承链路.
	if span, ok := i.Values().Get(middlewares.TracingSpan).(log.Span); ok {
		ctx = span.GetContext()
	} else {
		ctx = i.Request().Context()
	}

	// 1. 加载鉴权.
	auth = authorizer.New().Get(i)

	// 2. 读取钓场ID.
	if aid, err = master.GetArcadeId(i); err != nil {
		_ = i.JSON(result.New().WithError(err))
		return
	}

	// 3. 验证钓场.
	if arcade, admin, err = master.Verify(ctx, auth.UserId, aid); err != nil {
		_ = i.JSON(result.New().WithError(err))
		return
	}

	// 4. 验证通过.
	log.Infofc(ctx, `[middleware=master] verify arcade admin: user-id="%v", arcade-id="%v"`, admin.UserId, admin.ArcadeId)
	master.Set(i, arcade, admin)
	defer master.Unset(i)
	i.Next()
}
